var orgJurisdictionList = {};//部门权限
var orgId = 0;//当前部门
var userJurisdictionList = {};//当前用户权限

$(document).ready(function() {
    //加载完成后布局菜单自动适配页面
    $(".rightDiv").height($(window).height() * 0.8);
    $(".departmentPopupDiv").height($(window).height() * 0.75);
    $(".departmentListDiv").get(0).style.maxHeight = ($(window).height() * 0.6 + "px");

    //默认选中第一个部门
    $(".departmentRowDiv:first").click();
});

//修改信息转换按钮
$(".updateUserBtn").on('click',function(){
    //显示部分菜单
    $(".addUserDiv").show();
    $(".userInputBox").show();
    $(".uploadPicturesBtn").show();
    //隐藏部分菜单
    $(".updateUserDiv").hide();
    $(".userSpan").hide();
    //部门管理员
    var isManager =$("#isManagerDiv span").html();
    updateIsManagerDiv(0,isManager=="是"?1:0);
    //模块权限
    updateUserJurisdictionDiv(0, orgJurisdictionList);
});


//删除用户
$(".deleteUserBtn").on('click',function(){
    WeKnow.confirm('确定删除？', function() {
        var doctorUUID = $("#doctorUUID").val();
        $.ajax({
            type: "POST",
            url: "invs_system_setting.do/deleteUser",
            dataType: "json",
            data: {
                doctorUUID: doctorUUID
            },
            async: false,
            success: function(data) {
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
                if (data.errCode == 1) {
                    WeKnow.successMsg('删除成功');
                    //刷新页面
                    setTimeout(function () {
                        window.location.reload();
                    }, 1000);
                } else {
                    WeKnow.errorMsg(data.errMsg ? data.errMsg : "删除失败");
                }
            },
            error: function() {
                WeKnow.systemMsg('系统异常');
            }
        });


    });
});


//保存用户
$(".saveAddUserBtn").on('click',function(){
    //获取当前用户ID
    var doctorUUID = $("#doctorUUID").val();
    var param = {};
    //获取参数
    param.orgId = orgId;
    param.doctorUUID = doctorUUID;
    param.infoImg = $("#userInfoImg")[0].src;
    param.name =  $("#userNameDiv input").val();
    param.cell =  $("#userCellDiv input").val();
    param.loginName =  $("#userLoginNameDiv input").val();
    param.loginPass =  $("#userLoginPassDiv input").val();
    param.isManager = $("[name='isManager']:checked").val();
    var jurisdictionList = $("[name='userJurisdiction']:not(:checked)")
    var menuIdList = [];
    for(var index=0;index<jurisdictionList.length;index++){
        menuIdList.push(jurisdictionList[index].value)
    }
    param.menuIdList = menuIdList;
    if (param.name.length < 1) {
        WeKnow.errorMsg('名称不能为空');
        return false;
    }
    if (param.cell.length != 11) {
        WeKnow.errorMsg('手机号格式不正确，请输入11位手机号');
        return false;
    }
    if (param.loginName.length < 3) {
        WeKnow.errorMsg('登录账号长度至少有3位');
        return false;
    }
    var url = "";
    if(doctorUUID.length > 0){
        url = "invs_system_setting.do/updateUser";
    }else{
        url = "invs_system_setting.do/addUser";
        if (param.loginPass.length < 6) {
            WeKnow.errorMsg('密码至少有6位');
            return false;
        }
    }
    //请求接口
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: param,
        async: false,
        success: function(data) {
            if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
            if(data.errCode == 1){
                WeKnow.successMsg('保存成功');
                //刷新页面
                setTimeout(function () {
                    window.location.reload();
                }, 1000);
            }else{
                WeKnow.errorMsg(data.errMsg);
            }
        },
        error: function() {
            WeKnow.notifyMsg('操作失败，请稍后再试');
        }
    });

});


//上传头像文件-div触发file
$(".uploadPicturesBtn").on('click',function(){
    $("#uploadPicturesFile").click();
});

//关闭用户弹窗
$('.cancelAddUserBtn').on('click',function(){
    $(".userPopupDiv").hide(500);
});

//上传头像文件file内容变更
$("#uploadPicturesFile").change(function (e) {
    if($(this).val()){
        //手动清空不执行,存在文件调取接口上传OSS服务器获得访问地址
        var file = e.target.files[0];
        if(file.size > 1 * 1024 * 1024){
            WeKnow.notifyMsg("上传头像文件大小不能大于1MB");
            //清空文件
            $("#uploadPicturesFile").val("");
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file); //读出 base64
        reader.onloadend = function () {
            // 图片的base64值
            var base64 = "data:image/png;base64," + reader.result.substring(reader.result.indexOf(",")+1);
            $("#userInfoImg").attr("src", base64);
        };
    }
});

//打开用户弹窗
$('.rightDiv').on('click','.userRowDiv',function(){
    //获取数据
    var doctorUUID = $(this).data("user_id");
    if(doctorUUID){
        //获取资料
        var userHeadImgUrl = $(this).data("user_head_img_url");
        var doctorName = $(this).data("doctor_name");
        var doctorPhone = $(this).data("doctor_phone");
        var loginUser = $(this).data("login_user");
        var orgName = $(this).data("org_name");
        var isManager = $(this).data("is_manager");
        var jurisdictionName = $(this).data("jurisdiction_name");
        var jurisdiction = "" + $(this).data("jurisdiction");
        userJurisdictionList = jurisdiction.split(',');
        //填充数据
        $("#doctorUUID").val(doctorUUID);
        $("#userInfoImg").attr('src',userHeadImgUrl);
        $("#userNameDiv span").html(doctorName);
        $("#userCellDiv span").html(doctorPhone);
        $("#userLoginNameDiv span").html(loginUser);
        $("#userOrgNameDiv span").html(orgName);
        //填充修改资料
        $("#userNameDiv input").val(doctorName);
        $("#userCellDiv input").val(doctorPhone);
        $("#userLoginNameDiv input").val(loginUser);
        $("#userOrgNameDiv input").val(orgName);
        //显示部分菜单
        $(".updateUserDiv").show();
        $(".userSpan").show();
        //隐藏部分菜单
        $(".addUserDiv").hide();
        $(".userInputBox").hide();
        $(".uploadPicturesBtn").hide();
        //部门管理员
        updateIsManagerDiv(1,isManager);
        //模块权限
        updateUserJurisdictionDiv(1,jurisdictionName);
    }else{
        //新增用户-清空数据
        $("#doctorUUID").val("");
        $(".userInputBox").val("");
        var orgName = $(this).data("org_name");
        $("#userOrgNameDiv span").html(orgName);
        //部门管理员
        updateIsManagerDiv(0,0);
        //模块权限
        updateUserJurisdictionDiv(0, orgJurisdictionList);
        //清除头像文件
        $("#userInfoImg").attr("src", "img/userPhoto.png");
        $("#uploadPicturesFile").val("");
        //清空模块权限
        $("[name='userJurisdiction']").prop("checked",false);
        //显示部分菜单
        $(".addUserDiv").show();
        $(".userInputBox").show();
        $(".uploadPicturesBtn").show();
        //隐藏部分菜单
        $(".updateUserDiv").hide();
        $(".userSpan").hide();
    }
    //打开窗口
    $(".userPopupDiv").show(500);
});

function updateIsManagerDiv(type,status){
    if(type == 1){
        //显示内容
        if(status == 1){
            $("#isManagerDiv").html("<span style='margin-left: 20px;'>是</span>");//是管理员
        }else{
            $("#isManagerDiv").html("<span style='margin-left: 20px;'>否</span>");//不是管理员
        }
    }else{
        //显示控件
        var readonly = "";
        if($("#isManager").val() == 0) {
            //普通用户无操作权限
            readonly = 'onclick="return false"';
        }
        if(status == 1){
            var html = '<input type="radio" name="isManager" class="userInfoRadio" value="1" style="margin: 0px 10px;" checked '+readonly+'>是' +
                '<input type="radio" name="isManager" class="userInfoRadio" value="0" style="margin: 0px 10px;" '+readonly+'>否';
            $("#isManagerDiv").html(html);
        }else{
            var html = '<input type="radio" name="isManager" class="userInfoRadio" value="1" style="margin: 0px 10px;" '+readonly+'>是' +
                '<input type="radio" name="isManager" class="userInfoRadio" value="0" style="margin: 0px 10px;" checked '+readonly+'>否';
            $("#isManagerDiv").html(html);
        }
    }
}

function updateUserJurisdictionDiv(type,jurisdictionName){
    if(type == 1){
        //显示内容
        var html = "<span style='margin-left: 20px;'>" + jurisdictionName + "</span>";
        $("#userJurisdictionDiv").html(html);
    }else{
        //显示控件
        var readonly = "";
        if($("#isManager").val() == 0) {
            //普通用户无操作权限
            readonly = 'onclick="return false"';
        }
        var html = "";
        for(var i in jurisdictionName){
            var onJurisdiction = false;
            for(var j in userJurisdictionList){
                if(jurisdictionName[i].id == userJurisdictionList[j]){
                    //当前员工拥有该权限
                    onJurisdiction = true;
                }
            }
            html += '<div class="userInfoCheckboxDiv">';
            html += '<input type="checkbox" name="userJurisdiction" class="userInfoCheckbox" value="'+ jurisdictionName[i].id +'" '
            if(onJurisdiction){
                html += 'checked ';
            }
            html += 'style="margin: 0px 10px;" '+readonly+'>';
            html += jurisdictionName[i].name;
            html += '</div>';
        }
        $("#userJurisdictionDiv").html(html);
    }
}

//关闭用户弹窗
$('.userRightDiv span').on('click',function(){
    $(".userPopupDiv").hide(500);
});

//删除部门
$('.deleteDepartmentBtn').on('click',function(){
    //获取部门ID
    var orgId = $(this).closest("tr").data("id");
    WeKnow.confirm('确定删除？', function() {
        //请求接口
        $.ajax({
            type: "POST",
            url: "invs_system_setting.do/deleteOrg",
            dataType: "json",
            data: {
                orgId: orgId
            },
            async: false,
            success: function(data) {
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
                if(data.errCode == 1){
                    WeKnow.successMsg('删除成功');
                    //刷新页面
                    setTimeout(function () {
                        window.location.reload();
                    }, 1000);
                }else{
                    WeKnow.errorMsg(data.errMsg);
                }
            },
            error: function() {
                WeKnow.notifyMsg('操作失败，请稍后再试');
            }
        });
    });
});

//修改部门
$('.updateDepartmentBtn').on('click',function(){
    //获取数据
    var departmentId = $(this).closest("tr").data("id");
    var departmentName = $(this).closest("tr").data("name");
    var jurisdiction = "" + $(this).closest("tr").data("jurisdiction");
    $("#departmentId").val(departmentId);
    $(".addDepartmentNameInput").val(departmentName);
    if(jurisdiction){
        if(jurisdiction == "all"){
            //全部权限
            $(".jurisdictionCheckbox").prop("checked",true);
        }else{
            //部分权限
            var jurisdictionIds = jurisdiction.split(',');
            //清空全部权限选中
            $(".jurisdictionCheckbox").prop("checked",false);
            //遍历权限集合展示
            for(var index in jurisdictionIds){
                $(".jurisdictionCheckbox[value='"+jurisdictionIds[index]+"']").prop("checked",true);
            }
        }
    }else{
        //无任何权限
        $(".jurisdictionCheckbox").prop("checked",false);
    }
    //打开窗口
    $(".addDepartmentDiv").show(500);
});

//关闭添加部门窗口
$('#closeAddDepartmentDiv').on('click',function(){
    //关闭窗口
    $(".addDepartmentDiv").hide(500);
});

//保存新增部门
$('#saveAddDepartmentDiv').on('click',function(){
    //获取信息
    var orgId = $("#departmentId").val();
    var orgName = $("#departmentName").val();
    var jurisdictionList = $(".jurisdictionCheckbox:not(:checked)")
    var menuIdList = [];
    for(var index=0;index<jurisdictionList.length;index++){
        menuIdList.push(jurisdictionList[index].value)
    }
    var url = orgId?"invs_system_setting.do/updateOrgJurisdiction":"invs_system_setting.do/addOrg";
    //修改部门信息
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: {
            orgId: orgId,
            orgName: orgName,
            menuIdList: menuIdList
        },
        async: false,
        success: function(data) {
            if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
            if(data.errCode == 1){
                WeKnow.successMsg('保存成功');
                //刷新页面
                setTimeout(function () {
                    window.location.reload();
                }, 1000);
            }else{
                WeKnow.errorMsg(data.errMsg);
            }
        },
        error: function() {
            WeKnow.notifyMsg('操作失败，请稍后再试');
        }
    });
});

//打开新增部门窗口
$('.addDepartmentBtn').on('click',function(){
    //清空数据
    $("#departmentId").val("");
    $(".addDepartmentNameInput").val("");
    $(".jurisdictionCheckbox").prop("checked",false);
    //打开窗口
    $(".addDepartmentDiv").show(500);
});

//关闭部门管理窗口
$('.closeDepartmentInfoListDiv').on('click',function(){
    //关闭窗口
    $(".addDepartmentDiv").hide(500);
    $(".departmentInfoListDiv").hide(500);
    $(".popupDiv").hide(500);
});

//打开部门设置窗口
$('.departmentTitle_2').on('click',function(){
    //打开窗口
    $(".departmentInfoListDiv").show();
    $(".popupDiv").show(500);
});

//左侧部门菜单变更
$('.departmentRowDiv').on('click',function(){
    //剔除全部选中样式
    $(".departmentRowDiv").removeClass("selectDepartment");
    //选中当前
    $(this).addClass("selectDepartment");
    orgId = $(this).data("org_id");
    var orgName = $(this).html();
    //获取部门相关用户
    MY_SYSTEM_SETTING.getUserByOrgId(orgId,orgName);
});

var MY_SYSTEM_SETTING = (function() {

    //获取部门相关用户
    function getUserByOrgId(orgId,orgName) {
        //清空列表
        $(".rightDiv").html("");
        //请求接口获取数据
        $.ajax({
            type: "POST",
            url: "invs_system_setting.do/getUserList",
            dataType: "json",
            data: {
                orgId: orgId
            },
            async: false,
            success: function(data) {
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
                if(data.errCode == 1){
                    var e = '';
                    var staffs = data.staffs;
                    if (staffs && staffs.length) {
                        $(staffs).each(function(idx, staff) {
                            e += '<div class="userRowDiv" data-user_id="'+ staff.doctorUUID +'" ' +
                                'data-user_head_img_url="'+ staff.doctor.headImgUrl +'" ' +
                                'data-doctor_name="'+ staff.doctor.name +'" ' +
                                'data-doctor_phone="'+ staff.doctor.phone +'" ' +
                                'data-login_user="'+ staff.account.loginUser +'" ' +
                                'data-org_name="'+ staff.org.name +'" ' +
                                'data-is_manager="'+ staff.isManager +'" ' +
                                'data-jurisdiction="'+ staff.jurisdiction +'" ' +
                                'data-jurisdiction_name="'+ staff.jurisdictionName +'">' +
                                '<img src="'+staff.doctor.headImgUrl+'" class="userPhotoImg">' +
                                '<div class="userNameDiv">'+ staff.doctor.name +'</div>' +
                                '</div>';
                        });
                    }
                    //判断是否管理员
                    if(true){
                        e += '<div class="userRowDiv" data-org_name="'+ orgName +'" ><img src="img/addUser.png" class="userPhotoImg"></div>'
                    }
                    $(".rightDiv").append(e);
                    //部门权限更新
                    orgJurisdictionList = data.orgJurisdictionList;
                }else{
                    WeKnow.errorMsg(errMsg);
                    //清除部门权限
                    orgJurisdictionList = data.orgJurisdictionList;
                }
            },
            error: function() {
                WeKnow.notifyMsg('当前部门成员0位');
                //清除部门权限
                orgJurisdictionList = {};
            }
        });
    }
    return {
        getUserByOrgId:getUserByOrgId
    }
})();



